<?php

namespace control;
// 管理员后台-组装单
class assemblyClass extends adIndexClass
{
    private const page = 'assembly';
    private const table = 'inventory_assembly';
    private const tableMx = 'inventory_assembly_detail';
    private const tableRecord = 'inventory_record';
    private const title = '组装单';
    private const state = ['草稿', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "组合件",
                        'width' => 150,
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 200,
                    ],
                    'unit'  => [
                        'name'  => "单位",
                        'width' => 150,
                    ],
                    'num'  => [
                        'name'  => "数量",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'cost'         => [
                        'name'  => '子件成本（' . static::$unit . '）',
                        'width' => 100,
                    ],
                    'assemblyFee'          => [
                        'name'  => '组装费用（' . static::$unit . '）',
                        'width' => 200,
                    ],
                    'assemblyCost'          => [
                        'name'  => '组装成本（' . static::$unit . '）',
                        'width' => 180,
                    ],
                    'orderDate'          => [
                        'name'  => '单据日期',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 180,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "组合件"   => text(array("name" => "materialName")),
                    "规格型号"   => text(array("name" => "model")),
                ],
                [
                    "单据日期" => text(array("name" => "orderDate", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 列表-查询条件
     *
     * @return string
     */
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): string
    {
        //查询结果
        $where = " coid = '" . self::$coid . "' ";
        $and = search([
            'like' => [
                'name'  => $this->post('materialName'),
                'model' => $this->post('model'),
            ],
        ]);
        if ($and) {
            $where .= " AND materialId in (SELECT id FROM material WHERE 1=1 $and) ";
        }
        //生成查询语句
        $where .= search([
            "="    => [
                'orderNo' => $this->post('orderNo'),
            ],
            "like" => [
                'state' => $this->post('state'),
            ],
        ]);
        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array(
                    "title" => self::title . "详情",
                    "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",
                ),
                "edit"   => $array['state'] == '草稿' ? [
                    "title" => "编辑",
                    "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')",
                ] : [],
            );
            // 组装费
            $assemblyFee   = $array['fee'];
            $assemblyMoney = inventoryBalanceClass::assemblyCost($array['id']);
            // 子件成本
            $cost = $assemblyMoney['cost'];
            //组装成本
            $assemblyCost = $assemblyMoney['assemblyCost'];
            $material     = query('material', " id = '$array[materialId]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'cost':
                        $row[] = self::lostZero($cost);
                        break;
                    case 'assemblyFee':
                        $row[] = self::lostZero($assemblyFee);
                        break;
                    case 'assemblyCost':
                        $row[] = self::lostZero($assemblyCost);
                        break;
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num,ifnull(sum(fee),0) as fee",
        ]);
        $assemblyCost = find([
            'table'  => 'inventory_assembly_detail',
            'single' => "orderId in (select id from ".self::table." where {$where})",
            'field'  => "IFNULL(SUM(num*price),0) as total",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'cost'        => self::formattingFigure($assemblyCost['total'] + $totalQuery['fee']),
            'assemblyFee'        => self::lostZero($totalQuery['fee']),
            'assemblyCost'        => self::formattingFigure($assemblyCost['total']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result     = json_decode($resultJson, true);
        if ($result['warn'] == 2) {
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id       = $this->get('id');
        $info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name"  => "保存",
            "type"  => "点击事件",
            "title" => "保存",
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $button[] = [
            "name"  => "保存并提交",
            "type"  => "点击事件",
            "title" => "保存",
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $tr[]     = ['', '物料编码', '物料名称', '规格型号', '单位', '仓库', '仓位', '批号', '出库数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '备注'];
        $result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
        $totalArr = ['num'=>0,'money'=>0];
        foreach ((array)$result['array'] as $k=>$array) {
            $material = query('material', " id = '$array[materialId]'");
            $money    = self::formattingFigure($array['num'] * $array['price']);
            $tr[]     =
                [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
                    hidden(['name' => 'concatId[]', 'value' => $array['positionId'] . '-' . $array['materialId'] . '-' . $array['batch']]),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    warehouseClass::getName($array['warehouseId']),
                    warehousePositionClass::getName($array['positionId']),
                    $array['batch'],
                    text(['name' => 'mxNum[]', 'blur' => 'countMoney', 'value' => self::lostZero($array['num'], 'numPrecision'), 'other' => self::digitalFiltering('numPrecision')]),
                    hidden(['name' => 'mxPrice[]', 'value' => self::lostZero($array['price'], 'pricePrecision'), 'other' => self::digitalFiltering('pricePrecision')]) . $array['price'],
                    "<span class='total'>$money</span>",
                    text(['name' => 'mxText[]', 'value' => $array['text'],]),
                ];
            $totalArr['num'] += $array['num'];
            $totalArr['money'] += $money;
        }
        $total = [
            8 => "<span id='total_num'>".self::lostZero($totalArr['num'],'numPrecision')."</span>",
            10 => "<span id='total_money'>".self::lostZero($totalArr['money'],'numPrecision')."</span>",
        ];
        $table  = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $page  = self::page;
        $but = <<<EOT
		    <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())">选择物料</span>
		EOT;

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . '组合件' =>
                        hidden(['name' => 'materialId', 'value' => $info['materialId']]) .
                        '<span id="materialName">' . ($info['materialId'] ? dismantleClass::materialName($info['materialId'])['name'] : '未选择') . '</span>' .
                        "<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addMaterial',{})\" style='margin-left: 10px'>选择</span>",
                    must . '仓库'   => selectMultiple([
                            'table'    => 'warehouse',
                            "title"    => '入库仓库',
                            'sqlField' => 'name',
                            'sqlId'    => 'id',
                            'name'     => 'warehouseId',
                            'value'    => $info['warehouseId'],
                            "where"    => " coid = '" . self::$coid . "' and state = '启用' ",
                            'change'   => 'assign'
                        ]) . hidden(['name' => 'warehouse', 'value' => $info['warehouse']]),
                    must . '组装数量' => text([
                        'name'  => "num",
                        'class' => 'text',
                        'other' => self::digitalFiltering('numPrecision'),
                        'blur'  => 'countInventoryCost',
                        'value' => self::lostZero($info['num'], 'numPrecision')
                    ]),
                    must . '材料费用' => text([
                        'name'  => "materialCost",
                        'class' => 'text',
                        'other' => 'readonly' . self::digitalFiltering(),
                        'unit'  => '元',
                        'value' => self::lostZero($info['materialCost'])
                    ]),
                ],
                [
                    '组装费用' => text([
                        'name'  => "fee",
                        'blur'  => 'countInventoryCost',
                        'other' => self::digitalFiltering(),
                        'class' => 'text',
                        'unit'  => '元',
                        'value' => self::lostZero($info['fee'])
                    ]),
                    '入库单价' => text([
                        'name'  => "inventoryPrice",
                        'class' => 'text',
                        'other' => self::digitalFiltering('pricePrecision'),
                        'unit'  => '元',
                        'value' => self::lostZero($info['inventoryPrice'], 'pricePrecision')
                    ]),
                    '入库金额' => "<span id='inventoryMoney'>" . self::lostZero($info['inventoryMoney']) . "</span>" .
                        hidden(['name' => 'inventoryMoney', 'value' => $info['inventoryMoney']]),
                    must . '单据日期' => text(['name' => "orderDate", 'class' => 'text', 'value' => $info['orderDate'] ?: $this->date, 'laydate' => [],]),
                ],
                [
                    '备注'          => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '选择明细',
            'button' => $but,
            'html' => $table,
        ]);
        $data['html'] = $this->pageEdit([
            "html"  => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<EOT
		<script>
		//计算金额，税额等
        function countMoney(e){
            let obj = $(e).parent().parent()
            let num = obj.find('[name="mxNum[]"]').val(),
                price = obj.find('[name="mxPrice[]"]').val()
            let total = num * price
            obj.find(".total").html(total.toFixed(amountPrecision))
            materialCostSum()
            calculateTotal()
        }
        //材料费用汇总
        function materialCostSum() {
            var moneyAll = 0;
            $(".editList").find(".total").each(function () {
                var money = parseFloat($(this).text());
                moneyAll += money;
            });
            $("[name='materialCost']").val(moneyAll.toFixed(amountPrecision))
            countInventoryCost()
        }
        //计算入库单价和入库金额
        function countInventoryCost() {
          let num = $("[name='num']").val()*1
          let materialCost = $("[name='materialCost']").val()*1
          let fee = $("[name='fee']").val()*1
          let price = num===0?0:(materialCost+fee)/num
          let money = num*price
          $("[name='inventoryPrice']").val(price.toFixed(publicSettings.pricePrecision.num))
          $("[name='inventoryMoney']").val(money.toFixed(amountPrecision))
          $("#inventoryMoney").text(money.toFixed(amountPrecision))
        }
		//选择明细
		function addRow(){
			$.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
				$("#materialTable tbody").append(res.html);
				resetNumber($("#materialTable"))
			},'json');
		}
        function addMaterial(){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMaterialEdit', $("form[name='mxForm']").serialize(),function(resp) {
	         if (resp.warn === 2){
	            $('#assemblyAddMaterial').hide();
                $("[name='materialId']").val(resp.res.materialId);
	            $("#materialName").html(resp.res.name);
	         }else{
	             msg(res.warn);
	         }
	        },'json');
        }
        //计算总数量
        function calculateTotal(){
            let table = $('.editList')
            let num = 0,
            money = 0
            table.find("[name='mxNum[]']").each(function(index){
                if($(this).val()){
                  num+=Number($(this).val());
                }
                var totalText = table.find(".total").eq(index).text()
                if(totalText){
                    money+=Number(totalText);
                }
            })
            $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
            $("#total_money").text(money.toFixed(amountPrecision));
        }
		</script>
EOT;
        //返回
        return $this->tab($data);
    }

    /**
     *选择生产产品
     *
     * @return bool|string
     */
    public function addMaterial(): bool|string
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = '';
        $data             = [
            'sub'    => " onclick=\"addMaterial()\" ",
            'hidden' => hidden(["name" => "selectType", "value" => 'radio'])
                . hidden(["name" => "warehouseId", 'value' => $this->post('outWarehouseId')]) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMaterialEdit(): bool|string
    {
        $materialId = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($materialId)) {
            $json['warn'] = '请选择物料';
        } else {
            $material = query('material', "id = '$materialId'");
            $json     = [
                'warn' => 2,
                'res'  => [
                    'name'       => $material['model'] . '-' . $material['name'],
                    'materialId' => $material['id'],

                ],
            ];
        }
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id          = $this->post('id') ?: self::getId();
        $mxIdArr     = $this->post('mxId') ?: [];
        $concatIdArr = $this->post('concatId');
        //$mxUnitArr        = $this->post('mxUnit');
        //$mxWarehouseIdArr = $this->post('mxWarehouseId');
        $mxNumArr   = $this->post('mxNum');
        $mxPriceArr = $this->post('mxPrice');
        //$assemblyFeeArr   = $this->post('assemblyFee');
        $mxTextArr = $this->post('mxText');

        $field      = [
            'warehouseId'    => $this->post('warehouseId'),
            'warehouse'      => $this->post('warehouse'),
            'materialId'     => $this->post('materialId'),
            'orderDate'      => $this->post('orderDate'),
            'num'            => $this->post('num'),
            'fee'            => $this->post('fee'),
            'materialCost'   => $this->post('materialCost'),
            'inventoryPrice' => $this->post('inventoryPrice'),
            'inventoryMoney' => $this->post('inventoryMoney'),
            'text'           => $this->post('text'),
        ];
        $annotation = [
            'warehouseId' => '仓库名称',
            'warehouse'   => '仓库名称',
            'materialId'  => '组合件',
            'orderDate'   => '单据日期',
            'num'         => '组装数量',
            //			'fee'           => '费用',
            //			'text'          => '备注',
            //			'commitTime'    => '提交时间',
            //			'confirmTime'   => '确认时间',
            //			'passTime'      => '审核通过时间',
            //			'state'         => '状态',
        ];
        $rules      = [
            'warehouseId' => 'required',
            'warehouse'   => 'required',
            'materialId'  => 'required',
            'orderDate'   => 'required|date',
            'num'         => 'required|numeric',
            //			'fee'           => 'required',
            //			'text'          => 'required',
            //			'commitTime'    => 'required',
            //			'confirmTime'   => 'required',
            //			'passTime'      => 'required',
            //			'state'         => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        $where = " coid = '" . self::$coid . "' AND id = '$id' ";
        $info  = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择组装明细';
        } elseif (static::is_null_array($concatIdArr)) {
            $json['warn'] = '请选择组装明细';
        } elseif (static::is_null_array($mxNumArr)) {
            $json['warn'] = '数量请填写完整';
        } elseif (static::is_null_array($mxPriceArr)) {
            $json['warn'] = '请确认单价';
        } /*elseif (static::is_null_array($assemblyFeeArr)) {
			$json['warn'] = '请输入组装费用';
		}*/ elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此组装单已确认，不能修改';
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            if (!$info['id']) {
                $orderNo      = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'ZZ' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ], $field);
                $field        = array_merge($field, [
                    'id'      => $id,
                    'orderNo' => $orderNo,
                    'state'   => '草稿',
                    'coid'    => self::$coid,
                    'stid'    => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field,]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //添加或更新报价单明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx                 = query(self::tableMx, "id = '$nid'");
                    $concatId           = explode('-', $concatIdArr[$k]);
                    $material           = query('material', "id = '$concatId[1]'");
                    $warehouse_position = query('warehouse_position', "id = '$concatId[0]'");
                    $mxNumArr[$k]       = self::formattingFigure($mxNumArr[$k], 'numPrecision');
                    $mxPriceArr[$k]     = self::formattingFigure($mxPriceArr[$k], 'pricePrecision');
                    if (!empty($mx['id'])) {
                        //更新

                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'coid'        => self::$coid,
                                'materialId'  => $material['id'],
                                'warehouseId' => $warehouse_position['orderId'],
                                'positionId'  => $warehouse_position['id'],
                                'batch'       => $concatId[2],
                                'num'         => $mxNumArr[$k],
                                'price'       => $mxPriceArr[$k],
                                'unit'        => $material['unit'],
                                'text'        => $mxTextArr[$k],
                            ],
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => self::tableMx,
                            "field" => [
                                'id'          => $nid,
                                'coid'        => self::$coid,
                                'orderId'     => $id,
                                'materialId'  => $material['id'],
                                'warehouseId' => $warehouse_position['orderId'],
                                'positionId'  => $warehouse_position['id'],
                                'batch'       => $concatId[2],
                                'num'         => $mxNumArr[$k],
                                'price'       => $mxPriceArr[$k],
                                'unit'        => $material['unit'],
                                'text'        => $mxTextArr[$k],
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * @return bool|string
     */
    public function addMx()
    {
        $html   =
            selectMultiple(array(
                'name' => 'warehouse',
                'title' => '仓库',
                'table' => 'warehouse',
                'where' => " coid = '" . self::$coid . "' AND state = '启用' ",
                'sqlId' => 'id',
                'sqlField' => 'name'
            )) .
            text(array("name" => "position", "title" => "仓位")) .
            text(array("name" => "code", "title" => "物料编码")) .
            text(array("name" => "materialName", "title" => "物料名称")) .
            materialClass::typeSelect(name: 'typeId') .
            text(array("name" => "batch", "title" => "批次")) .
            '&nbsp;&nbsp;' . checkbox(["name" => "bom", "value" => [1 => 'bom清单'], 'checked' => '',]) .
            hidden(['name' => 'materialId', 'value' => $this->post('materialId')]) .
            hidden(['name' => 'concatId', 'value' => implode(',', (array)$this->post('concatId'))]);
        $button = "<input onclick=\"addRow();$('#" . self::page . "AddMx').remove()\" type='button' class='searchSub m-l-5' value='提交'>";
        $html   = $this->search($html);
        return $this->layer(["title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
    }

    /**
     *添加物料
     */
    public function addMxSearch()
    {
        $concatId = $this->post('concatId') ? explode(',', $this->post('concatId')) : [];
        $where    = " 1=1 and coid = '" . self::$coid . "' and concat(positionId,'-',materialId,'-',batch) not in ('" . implode("','", $concatId) . "')";
        //查询bom清单下的物料
        if (!static::isNull($this->post('bom'))) {
            $bom = query('bom', "coid = '" . self::$coid . "' and materialId = '" . $this->post('materialId') . "' and isDefault = 1 and state = '启用'");
            if ($bom['id']) {
                $material = query("material", " id = '" . $this->post('materialId') . "' ");
                $bomMx    = machiningOrderClass::bomMx($bom['id'], '', 1, $material['unit']);
                $ids   = array_column($bomMx, 'materialId');
                $where      .= " and materialId in ('" . implode("','", $ids) . "') ";
            }
        }
        $mwhere = search([
            "like" => [
                'code'   => $this->post('code'),
                'name'   => $this->post('materialName'),
                'typePath' => $this->post('typeId'),
            ],
        ]);
        if ($mwhere) {
            $where .= " AND materialId IN (SELECT id FROM material WHERE coid = '" . self::$coid . "' $mwhere )  ";
        }
        $like  = [
            'batch' => $this->post('batch'),
        ];
        $equal = [
            'warehouseId' => $this->post('warehouse')
        ];
        if ($this->post('position')) {
            $where .= " AND positionId IN (SELECT id FROM warehouse_position WHERE coid = '" . self::$coid . "' and name like '%" . $this->post('position') . "%')  ";
        }
        $where       .= search([
                "like"  => $like,
                "equal" => $equal,
            ]);
        $fieldArr    = self::resolveField([
            'field' => '`id`, `coid`, `warehouseId`, `positionId`, `materialId`, batch, SUM(num) as num, `time`',
            'group' => 'positionId,materialId,batch',
        ]);
        $where       .= $fieldArr['group'] . " having sum(num)>0";
        $page        = $this->page([
            "table" => 'inventory_record',
            'field' => $fieldArr['field'],
            "where" => $where,
            'pageNum' => 9,
            "order" => " time desc"
        ]);
        $json['sql'] = $page['sql'];
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[]     = [$checkAll, '分类', '物料编码', '物料名称', '规格型号','单位', '仓库', '仓位', '批号', '库存'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate           = [
                "box" => ["name" => "mxId", "value" => $array['positionId'] . '-' . $array['materialId'] . '-' . $array['batch']],
            ];
            $material           = query('material', " id = '$array[materialId]'");
            $tr[]               = [
                $this->dominate($dominate),
                $material['typeName'],
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                warehouseClass::getName($array['warehouseId']),
                warehousePositionClass::getName($array['positionId']),
                $array['batch'],
                self::lostZero($array['num'], 'numPrecision'),
            ];
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择物料';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $concatId           = explode('-', $mxId);
                $material           = query('material', " id = '$concatId[1]'");
                $warehouse_position = query('warehouse_position', " id = '$concatId[0]'");
                $warehouseName          = warehouseClass::getName($warehouse_position['orderId']);
                $id                 = self::getId();
                $unitPrice          = self::lostZero(inventoryBalanceClass::unitPrice($material['id']), 'pricePrecision');
                //$inventoryNum   = inventoryBalanceClass::inventoryNum($material['id'], $warehouse['id'],$warehouse_position['id'],$concatId[2]);
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'concatId[]', 'value' => $mxId)),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    $warehouseName,
                    $warehouse_position['name'],
                    $concatId[2],
                    text(array('name' => 'mxNum[]', 'type' => 'text', 'blur' => 'countMoney', 'other' => self::digitalFiltering('numPrecision'), 'value' => '')),
                    $unitPrice.hidden(array('name' => 'mxPrice[]', 'value' => $unitPrice)),
                    "<span class='total'>0</span>",
                    text(array('name' => 'mxText[]', 'class' => 'text')),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data   = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] != '已确认') {
                if ($info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name"  => "编辑",
                        "type"  => "顶部页卡",
                        "title" => "编辑用户",
                        "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                    ];
                }
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name"  => "确认",
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "取消",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $mxtr[] = ['物料编码', '物料名称', '规格型号', '单位', '仓库', '仓位', '批次', '出库数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
            $totalArr = ['num'=>0,'money'=>0];
            foreach ($result['array'] as $array) {
                $material           = query('material', " id = '$array[materialId]'");
                $mxtr[]             = [$material['code'], $material['name'], $material['model'], $array['unit'], warehouseClass::getName($array['warehouseId']), warehousePositionClass::getName($array['positionId']), $array['batch'], self::lostZero($array['num'], 'numPrecision'), self::lostZero($array['price'], 'pricePrecision'), self::formattingFigure($array['num'] * $array['price']), $array['text']];
                $totalArr['num'] += $array['num'];
                $totalArr['money'] += self::formattingFigure($array['num'] * $array['price']);
            }
            $total_tr = [
                7 => self::lostZero($totalArr['num'], 'numPrecision'),
                9 => self::lostZero($totalArr['money']),
            ];
            $material    = query('material', "id = '{$info['materialId']}'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                [
                    [
                        "组合件" => $material['model'] . '-' . $material['name'] ,
                        "仓库"                          => $info['warehouse'],
                        "组装数量"                        => self::lostZero($info['num'], 'numPrecision'),
                        '材料费用（' . static::$unit . '）' => self::lostZero($info['materialCost']),
                    ],
                    [
                        '组装费用（' . static::$unit . '）' => self::lostZero($info['fee']),
                        '入库单价（' . static::$unit . '）' => self::lostZero($info['inventoryPrice'], 'pricePrecision'),
                        '入库金额（' . static::$unit . '）' => self::lostZero($info['inventoryMoney']),
                        "单据日期" => $info['orderDate'],
                    ],
                    [
                        "备注"   => pre($info['text']),
                    ],

                    [
                        "单据编号" => $info['orderNo'],
                        "制单人"  => self::findStaff($info['stid']),
                        "状态"   => $info['state']
                    ],
                ]
            ]);
            $data['html'] .= $this->detailList([
                'title' => '子件',
                'html' => $this->listTable(array('tr' => $mxtr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit(): string
    {
        $id    = $this->post('id');
        $info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state'       => '已确认',
            //			'checkId'     => self::$stid,
            'confirmTime' => $this->time,
        ];
        /***仓库允许零库存出库*/
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } else {
            $this->startTrans();
            if (empty($info['id'])) {
                $json['warn'] = '未找到此组装单';
            } else {
                if ($info['state'] != '待确认') {
                    $json['warn'] = '此组装单不是待确认状态，不能确认';
                } else {
                    $isPass       = true; // 事务通过标志
                    $json['warn'] = update([
                        "table" => self::table,
                        "field" => $field,
                        "where" => "id = '$info[id]'",
                    ]);
                    if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
                        $details = find([
                            'table' => self::tableMx,
                            'where' => " orderId = '{$info['id']}'",
                        ]);
                        foreach ($details['array'] as $key => $value) {
                            $mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialId'], $value['num'], $value['unit']);
                            // 判断库存
                            if (!$outAllowZero && inventoryBalanceClass::inventoryNum($value['materialId'], $value['warehouseId'], $value['positionId'], $value['batch']) - $mainUnitNum < 0) {
                                $json['warn'] = '物料【' . materialClass::getName($value['materialId']) . '】出库数量不能大于库存数量';
                                goto resp;
                            }
                            $bool = inventoryBalanceClass::inventoryControl($value['materialId'], $mainUnitNum, "down");  //最低库存控制
                            if ($bool !== true) {
                                $json['warn'] = $bool;
                                goto resp;
                            }
                            $changeId               = self::getId();
                            $fieldChange            = [
                                'id'               => $changeId,
                                'coid'             => self::$coid,
                                'type'             => '其他出库',
                                'classify'         => 0,
                                'targetId'         => '',
                                'sourceTargetName' => '',
                                'confirmTime'      => $this->time,
                                'reviewTime'       => $this->time,
                                'state'            => '已复核',
                                'stid'             => self::$stid,
                            ];
                            $userNo                 = codeTemplateClass::generateCode('outStock', [
                                'prefix' => 'CKD' . date('Ymd'),
                                'table'  => 'inventory_changes',
                                'field'  => 'orderNo',
                                'where'  => " and coid = '" . self::$coid . "'",
                                'index'  => $key + 1,
                            ], $fieldChange);
                            $fieldChange['orderNo'] = $userNo;
                            $warn                   = static::insert(array(
                                'table' => 'inventory_changes',
                                'field' => $fieldChange,
                            ));
                            if ($warn != '新增成功') {
                                $json['warn'] = "新增出库变动失败";
                                goto resp;
                            }
                            //生成出库变动记录
                            $avgPrice = inventoryBalanceClass::unitPrice($value['materialId']);
                            $material = query("material", " id = '" . $value['materialId'] . "' ", "name,unit");
                            $warn     = static::insert(array(
                                'table' => 'inventory_changes_detail',
                                'field' => $fieldChangeMx = [
                                    'id'            => self::getId(),
                                    'coid'          => self::$coid,
                                    'orderId'       => $changeId,
                                    'materialId'    => $value['materialId'],
                                    'orderNum'      => $mainUnitNum,
                                    'batch'         => $value['batch'],
                                    'num'           => $mainUnitNum,
                                    'unit'          => $material['unit'],
                                    'price'         => $avgPrice,
                                    'money'         => self::formattingFigure($avgPrice * $mainUnitNum),
                                    'sourceTable'   => '',
                                    'sourceId'      => '',
                                    'sourceNo'      => '',
                                    'warehouseId'   => $value['warehouseId'],
                                    'positionId'    => $value['positionId'],
                                ],
                            ));
                            if ($warn != '新增成功') {
                                $json['warn'] = "新增出库变动明细失败";
                                goto resp;
                            }
                            // 材料出库
                            insert([
                                'table' => self::tableRecord,
                                'field' => [
                                    'id'            => self::getNo(),
                                    'coid'          => self::$coid,
                                    'warehouseId'   => $value['warehouseId'],
                                    'positionId'    => $value['positionId'],
                                    'materialId'    => $value['materialId'],
                                    'batch'         => $value['batch'],
                                    'num'           => -1 * $mainUnitNum,
                                    'changesId'     => $fieldChangeMx['id'],
                                    'defaultPrice'  => $avgPrice,
                                ],
                            ]);
                            if (!empty($value['positionId'])) {
                                //判断库存是否用完，去掉入库id
                                inventoryBalanceClass::recordStockToLocation('', ['materialId' => $value['materialId'], 'warehouseId' => $value['warehouseId'], 'positionId' => $value['positionId'], 'batch' => $value['batch']]);
                            }
                        }
                        $material = query("material", " id = '" . $info['materialId'] . "' ");
                        if (empty($material['positionId']) || $info['warehouseId'] != $material['warehouse']) {
                            $material['positionId'] = inventoryBalanceClass::matchLocation($info['warehouseId']);
                            $material['warehouse']  = $info['warehouseId'];
                        }
                        $batch       = inStockClass::getBatchNo('组装入库');
                        $mainUnitNum = inventoryBalanceClass::toMainUnit($info['materialId'], $info['num']);
                        $bool        = inventoryBalanceClass::inventoryControl($info['materialId'], $mainUnitNum, "top");  //最高库存控制
                        if ($bool !== true) {
                            $json['warn'] = $bool;
                            goto resp;
                        }
                        //单位单价转换
                        $price = round((float)$info['num'] * (float)$info['inventoryPrice'] / (float)$mainUnitNum, 4);
                        inventoryDefaultClass::recordInventoryPrice($info['materialId'], $mainUnitNum, $price);//计算记录加权平均单价
                        $changeId               = self::getId();
                        $fieldChange            = [
                            'id'               => $changeId,
                            'coid'             => self::$coid,
                            'type'             => '其他入库',
                            'classify'         => 1,
                            'targetId'         => '',
                            'sourceTargetName' => '',
                            'confirmTime'      => $this->time,
                            'reviewTime'       => $this->time,
                            'state'            => '已复核',
                            'stid'             => self::$stid,
                        ];
                        $userNo                 = codeTemplateClass::generateCode('inStock', [
                            'prefix' => 'RKD' . date('Ymd'),
                            'table'  => 'inventory_changes',
                            'field'  => 'orderNo',
                            'where'  => " and coid = '" . self::$coid . "'",
                        ], $fieldChange);
                        $fieldChange['orderNo'] = $userNo;
                        $warn                   = static::insert(array(
                            'table' => 'inventory_changes',
                            'field' => $fieldChange,
                        ));
                        if ($warn != '新增成功') {
                            $json['warn'] = "新增入库变动失败";
                            goto resp;
                        }
                        //生成出库变动记录
                        $warn = static::insert(array(
                            'table' => 'inventory_changes_detail',
                            'field' => $fieldChangeMx = [
                                'id'            => self::getId(),
                                'coid'          => self::$coid,
                                'orderId'       => $changeId,
                                'materialId'    => $info['materialId'],
                                'orderNum'      => $mainUnitNum,
                                'batch'         => $batch,
                                'num'           => $mainUnitNum,
                                'unit'          => $material['unit'],
                                'price'         => $price,
                                'money'         => self::formattingFigure($price * $mainUnitNum),
                                'sourceTable'   => '',
                                'sourceId'      => '',
                                'sourceNo'      => '',
                                'warehouseId'   => $material['warehouse'],
                                'positionId'    => $material['positionId'],
                            ],
                        ));
                        if ($warn != '新增成功') {
                            $json['warn'] = "新增出库变动明细失败";
                            goto resp;
                        }
                        // 组合件入库
                        $recordId = self::getNo();
                        insert([
                            'table' => self::tableRecord,
                            'field' => [
                                'id'            => $recordId,
                                'coid'          => self::$coid,
                                'warehouseId'   => $material['warehouse'],
                                'positionId'    => $material['positionId'],
                                'materialId'    => $info['materialId'],
                                'batch'         => $batch,
                                'num'           => $mainUnitNum,
                                'changesId'     => $fieldChangeMx['id'],
                                'defaultPrice'  => $price,
                            ],
                        ]);
                        if (!empty($material['positionId'])) inventoryBalanceClass::recordStockToLocation($recordId, ['positionId' => $material['positionId']]);
                        // 补出入库记录
                        inventoryBalanceClass::otherToinventory(self::table, $id);
                        $this->commitTrans(); // 提交事务
                        auditingFollow([
                            "type"   => "组装单",
                            "typeId" => $info['id'],
                            "text"   => "【{$this->control['name']}】确认",
                        ]);
                        //添加日志
                        $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                        $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                        $this->logText(["type" => self::page, "text" => $text]);
                        //返回
                        $_SESSION['warn'] = $json['warn'];
                        $json['warn']     = 2;
                        $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
                    }
                }
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 取消
     */
    public function cancelEdit(): string
    {
        $id    = $this->post('id');
        $info  = query(self::table, " id = '$id'");
        $field = [
            'state'       => '草稿',
            //			'checkId'     => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有取消权限';
        } else {
            if (empty($info['id'])) {
                $json['warn'] = '未找到此组装单';
            } else {
                $json['warn'] = update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => "id = '$info[id]'",
                ]);
                if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                    auditingFollow(array(
                        "type"   => "组装单",
                        "typeId" => $info['id'],
                        "text"   => "【{$this->control['name']}】取消",
                    ));
                    //添加日志
                    $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $_SESSION['warn'] = $json['warn'];
                    $json['warn']     = 2;
                    $json['href']     = root . "control/adIndex.html?cla=" . $this->get(
                            'cla'
                        ) . "&fun=detail&id=" . $info['id'];
                }
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit(): string
    {
        $id    = $this->post('id');
        $info  = query(self::table, " id = '$id'");
        $field = [
            'state'      => '待确认',
            'commitTime' => $this->time,
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } else {
            if (empty($info['id'])) {
                $json['warn'] = '未找到此组装单';
            } else {
                if ($info['state'] != '草稿') {
                    $json['warn'] = '此组装单不是草稿状态，不能提交';
                } else {
                    $json['warn'] = update(array(
                        "table" => self::table,
                        "field" => $field,
                        "where" => "id = '$info[id]'",
                    ));
                    if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                        auditingFollow([
                            "type"   => "组装单",
                            "typeId" => $info['id'],
                            "text"   => "【{$this->control['name']}】提交",
                        ]);
                        //添加日志
                        $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                        $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                        $this->logText(["type" => self::page, "text" => $text]);
                        //返回
                        $_SESSION['warn'] = $json['warn'];
                        $json['warn']     = 2;
                        $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
                    }
                }
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): string
    {
        $act   = $this->post('act') ?? '';
        $pwd   = $word = false; // 需要密码
        $power = '';
        switch ($act) {
            case 'confirm':
                $act      = 'confirm';
                $msg      = '确认';
                $title    = '是否已确认此组装单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form     = self::page . 'OperateForm, detailForm';

                $word = true;
                break;
            case 'commit':
                $act      = 'edit';
                $msg      = '编辑';
                $title    = '是否确认提交此组装单？';
                $function = 'commitEdit';
                $form     = self::page . 'OperateForm, detailForm';

                $word = true;
                break;
            case 'cancel':
                $act      = 'cancel';
                $msg      = '撤回';
                $title    = '是否确认取消此组装单？';
                $function = 'cancelEdit';
                $form     = self::page . 'OperateForm, detailForm';

                $word = true;
                break;
            default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm, quoForm';

                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete(): string|false
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } else {
            if (empty($array)) {
                $json['warn'] = "你一个数据都没有选择呢";
            } else {
                $text  = "";
                $x     = 0;
                $array = is_array($array) ? $array : [$array];
                foreach ($array as $id) {
                    $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                    if ($info['state'] == '已确认') {
                        $warn = "删除失败：已确认，暂不能删除";
                    } else {
                        //最后删除基本参数
                        delete(array("table" => self::table, "where" => " id = '$id' "));
                        delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                        delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                        //返回
                        $warn = "删除成功";
                        $x++;
                    }
                    $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
                }
                //添加日志
                $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
                $this->logText(array("type" => self::page, "text" => $text));
                $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
            }
        }
        return json_encode($json, 320);
    }

}
